import React, {PureComponent} from 'react';
import {
  View,
  StyleSheet,
  Text,
  Keyboard,
  FlatList,
  RefreshControl,
  TouchableOpacity,
  ActivityIndicator,
  Image,
} from 'react-native';
import I18n from 'react-native-i18n';
import {connect} from 'react-redux';
import BaseComponent from '../base/BaseComponent';
import {TextButton} from '../../components/Button';
import {NormalHeader} from '../../components/NavigationHeader';
import {showToast} from '../../components/Toast';
import {userLogout} from '../../redux/action';
import Clipboard from '@react-native-community/clipboard';
import {queryNotifyList, readNotify} from '../../api/user';
import moment from 'moment';
//#FFCB26
class Auction extends BaseComponent {
  constructor(props) {
    super(props);

    this.state = {
      isRefreshing: false,
      messages: [],
      page: 1,
      size: 10,
      total: 0,
      isLoadMore: false,
    };
  }
  componentDidMount() {
    this.onRefresh();
  }

  onRefresh = async () => {
    this.setState({
      isRefreshing: true,
    });

    await this.getList();

    this.setState({
      isRefreshing: false,
    });
  };

  getList = async () => {
    let {page, size} = this.state;
    queryNotifyList({
      userToken: this.props.userInfo.token,
      page,
      size,
    })
      .then((res) => {
        var messages = res.data.rows.map((item) => {
          return {
            ...item,
          };
        });

        // messages = [...messages, ...messages, ...messages];
        // messages = [...messages, ...messages, ...messages];
        // messages = [...messages, ...messages, ...messages];

        if (page !== 1) {
          messages = this.state.messages.concat(messages);
        }
        console.log(messages);
        this.setState({
          messages: messages,
          total: res.data.pageInfo.total,
        });
      })
      .catch((err) => {
        console.log(err);
        showToast(err.msg || 'falied');
      });
  };

  listEndReached() {
    console.log('>>上拉加载>>>');
    const {page, isLoadMore, total, messages} = this.state;

    if (messages.length < total && !isLoadMore) {
      this.setState(
        {
          page: page + 1,
          isLoadMore: true,
        },
        () => {
          this.getList();
        },
      );
    }
  }

  clearAllMessage = () => {
    readNotify({
      allMessage: 1,
      userToken: this.props.userInfo.token,
    }).then((res) => {
      this.onRefresh();
      // let newMessages = this.state.messages.map((message) => {
      //   message.status = 1;
      //   return {
      //     ...message,
      //   };
      // });
      // this.setState({
      //   messages: newMessages,
      // });
    });
  };

  pressMessage = (item) => {
    readNotify({
      notifyId: item.notifyId,
      userToken: this.props.userInfo.token,
    }).then((res) => {
      console.log('更新状态');
      console.log(res);
      let newMessages = this.state.messages.map((message) => {
        if (message.notifyId == item.notifyId) {
          console.log('更新状态');
          message.status = 1;
        }
        return {
          ...message,
        };
      });
      this.setState({
        messages: newMessages,
      });
    });

    console.log(item);
    if (item.extra && item.extra.length != 0) {
      let page = JSON.parse(item.extra);
      if (page.page == 'auction') {
        this.props.navigation.navigate('Auction', {
          auction: {auctionId: page.id},
        });
      }
    }
  };

  _renderItem = (item) => {
    let message = item.item;

    return (
      <TouchableOpacity
        // disabled={message.status != 0}
        onPress={() => {
          console.log('-------s');
          this.pressMessage(message);
        }}
        style={{
          backgroundColor: message.status == 0 ? 'white' : 'rgb(220,220,220)',
          height: 80,
          alignItems: 'center',
          justifyContent: 'space-between',
          borderRadius: 5,
          marginBottom: 20,
        }}>
        <Text
          style={{
            marginTop: 10,
            color: '#525252',
            width: '100%',
            paddingLeft: 10,
            paddingRight: 10,
          }}>
          {message.content}
        </Text>
        <Text
          style={{
            width: '100%',
            textAlign: 'right',
            marginBottom: 10,
            paddingRight: 10,
            color: '#525252',
          }}>
          {moment(message.createTime).format('YYYY-MM-DD HH:mm:ss')}
        </Text>
        {message.status == 0 ? (
          <View
            style={{
              width: 8,
              height: 8,
              borderRadius: 4,
              backgroundColor: 'red',
              position: 'absolute',
              right: 5,
              top: 5,
            }}
          />
        ) : null}
      </TouchableOpacity>
    );
  };

  _renderEmptyView = () => (
    <View
      style={{
        //   backgroundColor: 'yellow',
        width: '100%',
        height: 300,
        alignItems: 'center',
        justifyContent: 'center',
      }}>
      <Image
        style={{width: 95}}
        source={require('../../assets/browser/empty.png')}></Image>
      <Text style={{color: 'white', padding: 20, alignSelf: 'center'}}>
        No messages yet
      </Text>
    </View>
  );

  _renderItemSeparatorComponent = () => (
    <View style={{height: 0, backgroundColor: 'transparent'}} />
  );

  footerComponent = () => {
    let showLoadingMore = this.state.total >= this.state.page * this.state.size;
    return this.state.messages.length == 0 ? null : (
      <View>
        <View
          style={{
            flexDirection: 'row',
            color: 'white',
            justifyContent: 'center',
          }}>
          {showLoadingMore ? (
            <ActivityIndicator size="small" animating={true} />
          ) : null}
          <Text style={{color: 'white', marginLeft: 10}}>
            {showLoadingMore ? 'loading more...' : 'no more data'}
          </Text>
        </View>
      </View>
    );
  };

  renderComponent = () => {
    let {messages, isRefreshing} = this.state;
    return (
      <View style={{flex: 1, backgroundColor: '#160231'}}>
        <NormalHeader
          navigation={this.props.navigation}
          text="Message"
          left={{
            icon: require('../../assets/common/common_back_white.png'),
            onPress: () => {
              Keyboard.dismiss();
              this.props.navigation.goBack();
            },
          }}
          right={{
            icon: require('../../assets/home/clear.png'),
            onPress: () => {
              this.clearAllMessage();
            },
          }}
        />
        <View style={{padding: 20, flex: 1}}>
          <FlatList
            showsVerticalScrollIndicator={false}
            style={{marginTop: 0}}
            data={messages}
            keyExtractor={(item, index) => item.notifyId} // 给定的item生成一个不重复的key
            renderItem={this._renderItem}
            ListEmptyComponent={this._renderEmptyView}
            ItemSeparatorComponent={this._renderItemSeparatorComponent}
            ListFooterComponent={this.footerComponent}
            onEndReached={() => this.listEndReached()}
            onEndReachedThreshold={0.2}
            contentContainerStyle={{flexGrow: 1}}
            ListFooterComponentStyle={{flex: 1, justifyContent: 'flex-end'}}
            refreshControl={
              <RefreshControl
                tintColor="white"
                refreshing={isRefreshing}
                onRefresh={this.onRefresh}
                colors={['#ff0000', '#00ff00', '#0000ff', '#3ad564']}
                progressBackgroundColor="#ffffff"
              />
            }
          />
          <View
            style={{
              width: '100%',
              height: this.props.widgetLayout.show
                ? this.props.widgetLayout.height
                : 0,
              marginTop: 10,
            }}></View>
        </View>
      </View>
    );
  };
}

const mapStateToProps = (state) => ({
  userInfo: state.User.userInfo,
  widgetLayout: state.Layout.widgetLayout,
});

const mapDispatchToProps = (dispatch) => ({
  userLogout: (item) => dispatch(userLogout()),
});

export default connect(mapStateToProps, mapDispatchToProps)(Auction);
